// 修改头像请求
async function editAvatarRequest(data) {
    const res = await $.ajax({
        url: 'http://localhost:8081/api/userAvatarEdit.php',
        type: 'put',
        data: data
    })

    // 渲染头像
    if (res.code === 1) {
        location.reload()
    } else {
        myAlert(false, res.msg)
    }
}

// 上传文件请求
async function uploadFileRequest(formData) {
    const res = await $.ajax({
        url: 'http://localhost:8081/api/uploadFile.php',
        type: 'post',
        data: formData,
        processData: false,
        contentType: false
    })
    return res
}

// 上传头像事件
document.querySelector('#file').addEventListener('change', async (e) => {
    const file = e.target.files[0]
    const formData = new FormData()
    formData.append('file', file)
    const res = await uploadFileRequest(formData)
    if (res.code === 1) {
        console.log(res)
        const avatar = res.data
        const user_id = JSON.parse(localStorage.getItem('userInfo')).id
        await editAvatarRequest({
            user_id,
            avatar
        })
    } else {
        myAlert(false, res.msg)
    }
})